import { cloneDeep } from 'lodash'
import axios from '@/utils/request'
import { filterObj, getToken, startTimeValue, endTimeValue, toLineName } from '@/utils'
import { message, Modal } from 'ant-design-vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { store } from '@/store'
import { h, createVNode } from 'vue'
export const ListMixinPm = {
  data () {
    return {
      // token header
      // tokenHeader: { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) },
      /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      queryParam: {},
      /* 数据源 */
      dataSource: [],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 20,
        pageSizeOptions: ['10', '20', '30', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + this.$t('common.total') + total + this.$t('common.piece')
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 排序参数 */
      isorter: {
        field: '',
        order: ''
      },
      /* 筛选参数 */
      filters: {},
      /* table加载状态 */
      loading: false,
      /* table选中keys */
      selectedRowKeys: [],
      /* table选中records */
      selectionRows: [],
      modalTitle: '',
      // fileList: [],
      uploadHeaders: {},
      tableKey: 0,
      showMore: false,
      fuzzySearch: '',
      needLoad: true,
      isEnvLocal: process.env.VUE_APP_CONFIG == 'local',
      tableHeight: 'calc(100vh - 320px)',
    }
  },
  created () {
    this.uploadHeaders = {
      Authorization: getToken()
    }
    if (this.needLoad) this.loadData()
  },
  methods: {
    async syncData (params, otherOperate) {
      this.$refs.syncDataModalRef.visible = true
      try {
        let res = await axios.postAction(this.url.sync, params)
        if (res.success) {
          message.success(res.msg || this.$t('other.dataSyncSuccess'))
          otherOperate ? this.otherOperate() : this.searchReset()
        } else {
          message.error(res.msg || this.$t('other.dataSyncFailRetAgain'))
        }
        this.$refs.syncDataModalRef.visible = false
      } catch {
        message.error(this.$t('other.dataSyncFailRetAgain'))
        this.$refs.syncDataModalRef.visible = false
      }
    },

    toggleMore () {
      this.showMore = !this.showMore
      this.fuzzySearch = ''
      this.queryParam = {}
      this.initTableHeight && this.initTableHeight()
    },
    loadData (arg) {
      if (!this.url.list) {
        message.error(this.$t('other.lackUrl'))
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      let params = this.getQueryParams()
      if (!params) return
      // 查询条件
      this.loading = true
      axios.postAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.data ? res.data.list ? res.data.list : Array.isArray(res.data) ? res.data : [] : []
          res.data && (this.ipagination.total = res.data.total || 0)
        }
        this.loading = false
        this.selectedRowKeys = []
      }).finally(() => {
        this.loading = false
        this.tableKey = Math.random()
      })

      if (this.storeName) {
        if (typeof this.storeName == 'string') {
          store.dispatch(this.storeName)
        } else if (Array.isArray(this.storeName)) {
          this.storeName.map(i => {
            store.dispatch(i)
          })
        }
      }
    },
    getQueryParams () {
      let param = this.showMore ? cloneDeep(this.queryParam) : {}
      if (!this.showMore) param[this.fuzzySearchName] = this.fuzzySearch
      console.log('____param',param);
      // // 时间格式化
      if (this.queryParam.time && this.queryParam.time.length) {
        param.startTime = startTimeValue(this.queryParam.time[0])
        param.endTime = endTimeValue(this.queryParam.time[1])
      }
      this.searchTimeAry && this.searchTimeAry.forEach(i => {
        if (this.queryParam[i] && this.queryParam[i].length) {
          param[`start${i}`] = startTimeValue(this.queryParam[i][0])
          param[`end${i}`] = endTimeValue(this.queryParam[i][1])
        }
        delete param[i]
      })
      this.multipleSelect && this.multipleSelect.forEach(i => {
        if (this.queryParam[i] && !this.queryParam[i].length) {
          param[i] = null
        }
      })
      delete param.time
      param.sortingFields = this.isorter.field ? [this.isorter] : null
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    searchQuery () {
      this.loadData(1)
    },
    // 重置
    searchReset () {
      this.queryParam = {}
      this.loadData(1)
    },
    onSelectChange (selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    checkboxProps (record) {
      return {
        disabled: record.status != 1,
        name: `${record.status}`
      }
    }, 
    onClearSelected () {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    async handleDelete (id, otherOperate, text, okText) {
      if (!this.url.delete) {
        message.error(this.$t('other.lackUrl'))
        return
      }

      const idList = id ? [id] : this.selectedRowKeys


      Modal.confirm({
        title: h('div', {class: 'confirm-modal-title'}, [h('div', this.$t('other.tips') )]),
        closable: true,
        icon: null,
        content:  h('div', {class: 'confirm-modal-content'}, [h('span', createVNode(<ExclamationCircleOutlined />)), h('span', text || this.$t('other.confirmDelDate')+'?')]),
        okText: okText || this.$t('common.ok'),
        onOk: async () => {
          axios.deleteAction(this.url.delete, idList).then(res => {
            if (res.success) {
              message.success(res.msg)
              if (otherOperate) {
                this.otherOperate()
              } else {
                this.loadData()
              }
            } else {
              message.warning(res.msg)
            }
          })
        },
        onCancel () { },

      });

    },
    async handleDelete1 (text) {
      Modal.confirm({
        title: h('div', {class: 'confirm-modal-title'}, [h('div', this.$t('other.tips') )]),
        closable: true,
        icon: null,
        content: h('div', {class: 'confirm-modal-content'}, [h('span', createVNode(<ExclamationCircleOutlined />)), h('span', text)]),
        onOk: async () => {

        },
        onCancel () { },

      });
    },
    async confirmChangeStatus (url, params, contentText, title = this.$t('other.tips'), optAct = 'postAction', otherOperate) {
      Modal.confirm({
        title: h('div', {class: 'confirm-modal-title'}, [h('div', title )]),
        closable: true,
        icon: null,
        content: h('div', {class: 'confirm-modal-content'}, [h('span', createVNode(<ExclamationCircleOutlined />)), h('span', contentText || this.$t('other.sureOperation')+'?')]),
        onOk: async () => {
          axios[optAct](url, params).then(res => {
            if (res.success) {
              message.success(res.msg)
              otherOperate ? this.otherOperate() : this.loadData()
            } else {
              message.warning(res.msg)
            }
          })
        },
        onCancel () { },

      });

    },
    async customChangeStatus (url, params) {
      try {
        const res = await axios.postAction(url, params)
        if (res.success) message.success(res.msg)
      } catch {
        console.log(222);
      }
      this.loading = false
      this.loadData()
    },
    async changeStatus (value, record, name) {
      const params = cloneDeep(record)
      params[name ? name : 'status'] = value ? 0 : 1
      const res = await axios.postAction(this.url.changeStatus || this.url.save, params)
      if (res.success) {
        this.loadData()
      } else {
        message.warning(res.msg || this.$t('common.errorTip'))
      }
    },
    // 操作
    async handleRequestEdit (id) {
      try {
        const res = await axios.getAction(this.url.detailUrl, { id })
        if (res.success) this.handleEdit(res.data)
      } catch (err) {
        message.warning(this.$t('other.getFailAgain'))
      }
    },
    // modal 对话框  record data数据对象  refName modal名字  isEdit false == add  true == edit
    modalDo (record = {}, refName, isEdit = false) {
      if (typeof this.initModalSelectOptions === 'function') {
        this.$refs[refName]?.initSelectOptions(this.initModalSelectOptions())
      }
      this.$refs[refName]?.edit(record, isEdit)
    },

    handleEdit (record, isEdit = true) {
      if (typeof this.initModalSelectOptions === 'function') {
        this.$refs.modalForm.initSelectOptions(this.initModalSelectOptions())
      }
      this.$refs.modalForm.edit(record, isEdit)
    },
    handleAdd () {
      this.handleEdit({}, false)
    },
    handleModalDetail (record) {
      this.$refs.modalForm.edit(record, true)
    },
    async handleRequestDetail (id) {
      try {
        const res = await axios.getAction(this.url.detailUrl, { id })
        if (res.success) this.handleDrawDetail(res.data)
      } catch (err) {
        message.warning(this.$t('other.getFailAgain'))
      }
    },
    handleDrawDetail (record) {
      this.$refs.detailForm.openDraw(record)
    },
    handleTableChange (pagination, filters, sorter) {
      // 分页、排序、筛选变化时触发
      // TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.field = sorter.order ? toLineName(sorter.field) : ''
        this.isorter.order = sorter.order ? sorter.order == 'ascend' ? 'asc' : 'desc' : ''
      }
      this.ipagination = Object.assign(this.ipagination, pagination)
      this.loadData()
    },
    handleToggleSearch () {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },
    modalFormOk () {
      this.loadData()
    },
    /* 导出 */
    handleExportXls2 () {
      let paramsStr = encodeURI(JSON.stringify(this.getQueryParams()))
      let url = `${window._CONFIG.domianURL}/${this.url.exportXlsUrl}?paramsStr=${paramsStr}`
      window.location.href = url
    },
    handleExportXls (exportUrl, fileName, needParams = false) {
      if (!fileName || typeof fileName != 'string') {
        fileName = this.$t('other.exportFile')
      }
      let param = this.getQueryParams()

      axios.downFile(exportUrl, needParams ? param : null).then((data) => {
        if (!data) {
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), fileName + '.xlsx')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
        }
      })
    },
    exportExcels (exportUrl, fileName, needParams = false, params) {
      if (!fileName || typeof fileName != 'string') {
        fileName = this.$t('other.exportFile')
      }
      // let param = this.getQueryParams()
      let param = params;

      axios.downFile(exportUrl, needParams ? param : null).then((data) => {
        console.log('*********', data);
        if (!data) {
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), fileName + '.xlsx')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
        }
      })
    },

    beforeUpload (file) {
      const { name } = file
      // 校验是否是excel文件
      const isExcel = /(xls|xlsx)$/i.test(name)
      if (!isExcel) {
        message.error(this.$t('other.onlyUploadFile'))
      }
      return isExcel
    },
    /* 导入 */
    handleImportExcel (info) {
      if (info.file.status !== 'uploading') {
        console.log('uploading')
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          // message.success(`${info.file.name} 文件上传成功`)
          this.loadData()
        } else {
          message.error(info.file.response.msg)
        }
      } else if (info.file.status === 'error') {
        message.error(`${this.$t('common.fileUploadErr')}: ${info.file.msg} `)
      }
    },
  }

}
